//
//  AppDelegate.m
//  SocietySale
//
//  Created by Mike on 16/10/25.
//  Copyright © 2016年 Mike. All rights reserved.
//

#import "AppDelegate.h"
#import "MSLeadViewController.h"
#import <UMSocialCore/UMSocialCore.h>

@interface AppDelegate ()

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    [self loadMainViewController];
    [self.window makeKeyAndVisible];

    //设置友盟社会化组件appkey（分享）
    [[UMSocialManager defaultManager] setUmSocialAppkey:UMENG_APPKEY];
    //微信好友、朋友圈分享
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:wechatAppID appSecret:wechatAppSecret redirectURL:@"http://m.weshare12.com"];
    //移除微信收藏
    [[UMSocialManager defaultManager] removePlatformProviderWithPlatformTypes:@[@(UMSocialPlatformType_WechatFavorite)]];
    //设置新浪的appKey和appSecret
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_Sina appKey:sinaAppKey  appSecret:sinaAppSecret redirectURL:@"http://sns.whalecloud.com/sina2/callback"];
    
    return YES;
}

#pragma mark - 启动信息
- (void)loadMainViewController
{
    //加载引导页
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    NSString *loginState = [ud objectForKey:LoginState];
    NSString *sessionId = [ud objectForKey:LoginSessionId];
    netEngine.sessionId = [HDUtil check:sessionId];

    if (!self.mainViewController) {
        self.mainViewController = [[MSMainViewController alloc] init];
    }
    self.nav = [[UINavigationController alloc] initWithRootViewController:self.mainViewController];
    self.nav.navigationBar.hidden=YES;
    self.window.rootViewController=self.nav;
    
    if (!loginState.length) {
        [netEngine requestStartImageWithTarget:nil hudView:nil];
        
        MSLeadViewController *leadVC = [[MSLeadViewController alloc] init];
        [rootNavigation pushViewController:leadVC animated:NO];
    }
}

/**
 * 这里处理新浪微博SSO授权之后跳转回来，和微信分享完成之后跳转回来
 */
//应用内（h5）跳回nativeAPP页面9.0之前(包括分享完例如微信跳转回来)
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    if ([[UMSocialManager defaultManager] handleOpenURL:url]) {

        return  YES;
    }
    return YES;
}

//应用内（h5）跳回nativeAPP页面9.0之后(包括分享完例如微信跳转回来)
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary *)options
{
    if ([[UMSocialManager defaultManager] handleOpenURL:url]) {
        return  YES;
    }
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    
    
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    
    
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    
    
}


- (void)applicationWillTerminate:(UIApplication *)application {
    
    
    [self saveContext];
}


#pragma mark - Core Data stack

@synthesize persistentContainer = _persistentContainer;

- (NSPersistentContainer *)persistentContainer {
    // The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it.
    @synchronized (self) {
        if (_persistentContainer == nil) {
            _persistentContainer = [[NSPersistentContainer alloc] initWithName:@"SocietySale"];
            [_persistentContainer loadPersistentStoresWithCompletionHandler:^(NSPersistentStoreDescription *storeDescription, NSError *error) {
                if (error != nil) {
                    // Replace this implementation with code to handle the error appropriately.
                    // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                    
                    /*
                     Typical reasons for an error here include:
                     * The parent directory does not exist, cannot be created, or disallows writing.
                     * The persistent store is not accessible, due to permissions or data protection when the device is locked.
                     * The device is out of space.
                     * The store could not be migrated to the current model version.
                     Check the error message to determine what the actual problem was.
                    */
                    NSLog(@"Unresolved error %@, %@", error, error.userInfo);
                    abort();
                }
            }];
        }
    }
    
    return _persistentContainer;
}

#pragma mark - Core Data Saving support

- (void)saveContext {
    NSManagedObjectContext *context = self.persistentContainer.viewContext;
    NSError *error = nil;
    if ([context hasChanges] && ![context save:&error]) {        
        NSLog(@"Unresolved error %@, %@", error, error.userInfo);
        abort();
    }
}

@end
